<script>
import { reactive } from "vue";
import { getDicMap } from "@/utils/storage";
import { useTzRouter } from "@/vhooks/useTzRouter";
import Taro from "@tarojs/taro";

export default {
  name: "CcrnLicence",
  components: {},
  setup() {
    const { navigateBack, route } = useTzRouter();
    const dicMap = getDicMap();
    const state = reactive({
      licenceForms: [{}],
      formsDisabled: false,
    });

    if (route.query.formsDisabled) {
      state.formsDisabled =
        route.query.formsDisabled === "false" ? false : true;
    }

    if (route.query?.permitsList && route.query.permitsList !== "undefined") {
      state.licenceForms = JSON.parse(route.query.permitsList);
    }

    // 是否空字符串
    const isEmpty = (str) => {
      if (typeof str === "number") {
        str = str.toString();
      }
      return (
        str === null || str === undefined || str.trim() === "" || str === "null"
      );
    };

    const validateListValue = (list) => {
      // 如果每一项成员都有值，返回true
      return list.some((item) => {
        // 判断每一项的成员是否有值
        return Object.values(item).some((subItem) => !!subItem);
      });
    };

    const handleSubmit = () => {
      try {
        for (let i = 0; i < state.licenceForms.length; i++) {
          if (Object.values(state.licenceForms[i]).some((item) => !!item)) {
            if (isEmpty(state.licenceForms[i].permitNumber)) {
              throw new Error("请输入许可证号");
            }
            if (isEmpty(state.licenceForms[i].issuingOrganization)) {
              throw new Error("请选择发证机构");
            }
            if (isEmpty(state.licenceForms[i].permitType)) {
              throw new Error("请选择许可证类型");
            }
          }
        }
        if (validateListValue(state.licenceForms)) {
          // 只要有一个成员有值
          navigateBack({
            delta: 1,
            event: {
              type: "licenceBack",
              data: {
                licenceForms: state.licenceForms,
                goodsIndex: route.query.goodsIndex,
              },
            },
          });
        } else {
          // 成员都没有值
          navigateBack({
            delta: 1,
            event: {
              type: "licenceBack",
              data: {
                licenceForms: [],
                goodsIndex: route.query.goodsIndex,
              },
            },
          });
        }
      } catch (err) {
        $TzNotify.danger(err.message);
      }
    };

    const handleAppend = () => {
      state.licenceForms.push({});
    };

    const handleDelete = (index) => {
      Taro.showModal({
        content: "确定删除该条记录吗？",
        confirmText: "确定",
        cancelText: "取消",
      }).then((res) => {
        if (res.cancel) return;
        state.licenceForms.splice(index, 1);
      });
    };

    const wrapText = (dom, text) => {
      return !state.formsDisabled ? (
        dom
      ) : (
        <tz-text class="break-text">{text}</tz-text>
      );
    };

    return () => (
      <tz-view class="ccrn-licence">
        <tz-view class="form-block">
          <tz-view class="handle-area">
            <tz-text class="form-block-title">许可证信息</tz-text>
            {!state.formsDisabled && (
              <tz-view class="handle-btn">
                <tz-button type="primary" plain onClick={handleAppend}>
                  增加许可证
                </tz-button>
              </tz-view>
            )}
          </tz-view>
          {state.licenceForms.map((item, index) => (
            <tz-form class="licence-form">
              <tz-cell title="序号" border>
                <tz-text class="no">{index + 1}</tz-text>
                {!state.formsDisabled && (
                  <tz-icon
                    onClick={() => handleDelete(index)}
                    class="tz-input-icon"
                    name="trash"
                  ></tz-icon>
                )}
              </tz-cell>
              <tz-cell title="许可证号" border>
                {wrapText(
                  <tz-input
                    disabled={state.formsDisabled}
                    v-model={item.permitNumber}
                    type="text"
                    placeholder="请输入许可证号"
                    clearable
                    maxlength="35"
                  />,
                  item.permitNumber
                )}
              </tz-cell>
              <tz-cell title="发证机构" border>
                <tz-picker
                  disabled={state.formsDisabled}
                  v-model={item.issuingOrganization}
                  mode="selector"
                  range={[{ code: "", nameCn: "请选择" }].concat(
                    dicMap.officeList
                  )}
                  rangeKey="nameCn"
                  valueKey="code"
                ></tz-picker>
              </tz-cell>
              <tz-cell title="许可证类型" border>
                <tz-search-picker
                  disabled={state.formsDisabled}
                  searchPlaceholder="请输入许可证类型"
                  v-model={item.permitType}
                  range={[{ code: "", nameCn: "请选择" }].concat(
                    dicMap.permissionTypeList
                  )}
                  rangeKey="nameCn"
                  valueKey="code"
                ></tz-search-picker>
              </tz-cell>
            </tz-form>
          ))}
        </tz-view>
        {!state.formsDisabled && (
          <tz-view class="btn-wrap">
            <tz-button type="primary" onClick={handleSubmit}>
              保存
            </tz-button>
            <tz-button
              type="default"
              onClick={() =>
                navigateBack({
                  delta: 1,
                })
              }
            >
              返回
            </tz-button>
          </tz-view>
        )}
      </tz-view>
    );
  },
};
</script>

<style lang="scss">
.ccrn-licence {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .form-block {
    width: 100%;
    display: flex;
    flex-direction: column;
    .form-block-title {
      padding: 13px 0 13px 21px;
      color: $title-color;
    }

    .handle-area {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .handle-btn {
        padding-right: 21px;
        .tz-button {
          width: 100px;
          height: 26px;
          background: #fff;
        }
      }
    }

    .licence-form {
      &:not(:first-child) {
        margin-top: 1px;
      }
      .tz-cell {
        .no {
          flex: 1;
        }
      }
    }

    .tz-form {
      background-color: $white;
      .tz-cell {
        line-height: unset;
        .tz-cell-label {
          text-align: right;
          padding: 13px 20px 13px 0;
        }
        .tz-cell-value {
          padding-right: 20px;
          .first-icon {
            margin-right: 15px;
          }
          .tz-icon {
            font-size: 20px;
          }
        }
        picker {
          .placeholder {
            color: $placeholder-color;
          }
        }
        .tz-icon-scan {
          color: $info-color-active;
        }
        &.arrow-cell {
          .tz-cell-value {
            justify-content: flex-end;
          }
        }
      }
    }
  }
  .btn-wrap {
    display: flex;
    width: 100%;
    padding: 27px 53px 29px;
    justify-content: space-between;
    .tz-button {
      width: 125px;
    }
  }
}
</style>
